import Resources from "./Resources"

export default class UI {
    static Child(node: cc.Node, path: string) {
        if (path == null) {
            return node
        }

        const paths = path.split('/')
        let child = node
        for (let index = 0; index < paths.length; index++) {
            child = child.getChildByName(paths[index])
            if (child == null) {
                console.log(`node: ${node.name} has no child: ${path}`)
                return null
            }
        }

        return child
    }

    static GetComponent<T extends cc.Component>(node: cc.Node, path, component: { prototype: T } = null): T {
        if (component == null) {
            [path, component] = [component, path]
        }

        const child = UI.Child(node, path)
        return child ? child.getComponent(component) : null
    }

    static Active(node: cc.Node, path: string | boolean, active: boolean = null) {
        active = typeof path == 'boolean' ? path : active
        path = typeof path == 'boolean' ? null : path

        const child = UI.Child(node, path)
        child && (child.active = active)
    }

    static on<T extends Function>(node: cc.Node, path: string, event: string, callback: T, target?: any, useCapture?: boolean): T {
        let child = UI.Child(node, path)
        return child.on(event, callback, target, useCapture)
    }

    static OnClick<T extends Function>(node: cc.Node, path: string, callback: T, target?: any, useCapture?: boolean): T {
        return UI.on(node, path, 'click', callback, target, useCapture)
    }

    static OnEditEnd<T extends Function>(node: cc.Node, path: string, callback: T, target?: any, useCapture?: boolean): T {
        return UI.on(node, path, 'editing-did-ended', callback, target, useCapture)
    }

    private static InitPrefabByPrefab(prefab: cc.Prefab, parent: cc.Node = null): cc.Node {
        const node = cc.instantiate(prefab)
        if (parent) {
            node.setParent(parent)
        }

        return node
    }

    static async InitPrefab(prefab: string | cc.Prefab, parent: cc.Node = null) {
        if (typeof prefab == 'string') {
            let loadedPrefab = await Resources.load(prefab)
            return UI.InitPrefabByPrefab(loadedPrefab as cc.Prefab, parent)
        }

        return UI.InitPrefabByPrefab(prefab, parent)
    }

    static async InitWindow(prefab: string | cc.Prefab) {
        let windowNode = await UI.InitPrefab(prefab)
        return windowNode
    }

    static Label(node: cc.Node, path: string, text: string = null) {
        if (text == null) {
            [path, text] = [text, path]
        }

        UI.GetComponent(node, path, cc.Label).string = text
    }
}
